use([
        'public/javascripts/service/order_manage_tradeService.js',
        'public/javascripts/widget/slider/slider.js',
        'public/javascripts/widget/prompt/prompt.js',
        'public/javascripts/widget/dialog/dialog.js',
        'public/javascripts/widget/calander/calander.js',
        'public/javascripts/widget/select/select.js'
    ],
    function(order_manage_tradeService, SliderComponent, PromptComponent, DialogComponent, Calander, selectFactory) {
        var PageComponent = React.createClass({
            componentDidMount: function() {
                Calander.init({
                    ele: ['#beginDate', '#endDate'],
                    isClear: true
                });

                self.refs.startTime.setValue(new Date().getBeforeDate(6)+' 00:00:00');
                self.refs.endTime.setValue(new Date().format("yyyy-MM-dd 23:59:59"));

                $('#beginDate').change(function(e) {
                    self.refs.startTime.setValue(e.target.value);
                });
                $('#endDate').change(function(e) {
                    self.refs.endTime.setValue(e.target.value);
                });
                if (cookie.get('userType') === '2' || cookie.get('userType') === '3') {
                    this.setState({ userType: 1 });
                    this.search({ orderStatus: 'DRAFT', sort: 'createTime', asc: false ,startTime:new Date().getBeforeDate(6)+' 00:00:00',endTime:new Date().format("yyyy-MM-dd 23:59:59")});
                    this.getSuppliers();
                }
                if (cookie.get('userType') === '256') {
                    this.setState({ userType: 2 });
                    this.search({ orderStatus: 'CONFIRMING', sort: 'createTime', asc: false,startTime:new Date().getBeforeDate(6)+' 00:00:00',endTime:new Date().format("yyyy-MM-dd 23:59:59")});
                    this.getPlat();
                    this.searchGoodsNo();
                }
                this.getSubAccount();
            },

            getInitialState: function() {
                return {
                    tabTitle: ['草稿', '待确认', '待发货', '待收货', '已签收'],
                    active: 0,
                    goodsType: [],
                    statusList: ['DRAFT', 'CONFIRMING', 'DELIVERY', 'TRANSPORT', 'SIGNED'],
                    orderStatus: 'DRAFT',
                    suppliers: [],
                    total: '',
                    list: '',
                    selectItem: [],
                    selectLength: 0,
                    orders: [],
                    currentTime: '',
                    current: 1,
                    pageSize: 10,
                    goodsInfo: [],
                    userList: [],
                    sellId: ''
                };
            },
            // 搜索
            search: function(param) {

                if (!param) {
                    param = {};
                }
                if (this.state.userType === 1) {
                    param.orderStatus = param.orderStatus ? param.orderStatus : this.state.statusList[this.state.active];
                }
                if (this.state.userType === 2 || this.state.userType === 3) {
                    param.orderStatus = param.orderStatus ? param.orderStatus : this.state.statusList[this.state.active + 1];
                }
                this.state.goodsType.forEach(function(item) {
                    if (item.name === param.goodsTypeId) {
                        param.goodsTypeId = item.id;
                    }
                });

                this.state.suppliers.forEach(function(item) {
                    if(param.customerId == '全部'){
                        param.customerId = '';
                    }else if ((item.nameCode && item.nameCode === param.customerId) || item.name === param.customerId) {
                        param.customerId = item.id;
                    }
                });


                this.state.goodsInfo.length &&
                    this.state.goodsInfo.forEach(function(item) {
                        if (item.name === param.goodsId) {
                            param.goodsId = item.id;
                        }
                    });
                if (param.cusUserId) {
                    this.state.userList.length &&
                        this.state.userList.forEach(function(item) {
                            if (item.nameCode === param.cusUserId) {
                                param.cusUserId = item.id;
                            }
                        });
                }
                var userType;
                if (cookie.get('userType') === '2' || cookie.get('userType') === '3') {
                    param.orderType = 'SALE';
                    userType = 1;
                }
                if (cookie.get('userType') === '256') {
                    param.orderType = 'PURCHASE';
                    userType = 2;
                }
                param.sort = 'createTime';
                param.asc = false;
                param.pageSize = param.pageSize ? param.pageSize : this.state.pageSize;
                var that = this;
                order_manage_tradeService.search({ urlParams: param, userType: userType, }, function(res) {
                    if (res.errorCode === 0) {
                        that.setState({
                            list: res.data,
                            total: res.pagination.totalResult
                        });
                    }
                });
            },
            // 切换页签
            toggleTab: function(index) {
                if (this.state.active === index) {
                    return;
                }
                this.setState({ active: index });
                var searchData = {};
                if (this.state.userType === 1) {
                    searchData.orderStatus = this.state.statusList[index];
                }
                if (this.state.userType === 2 || this.state.userType === 3) {
                    searchData.orderStatus = this.state.statusList[index + 1];
                }
                searchData.pageIndex = 1;
                this.refs.form.reset();

                this.refs.startTime.setValue(new Date().getBeforeDate(6)+' 00:00:00');
                this.refs.endTime.setValue(new Date().format("yyyy-MM-dd 23:59:59"));

                searchData.startTime = new Date().getBeforeDate(6)+' 00:00:00';
                searchData.endTime = new Date().format("yyyy-MM-dd 23:59:59");

                this.search(searchData);
                this.setState({ searchData: '', selectItem: [], selectLength: 0, current: 1 });
            },
            // 提交搜索条件
            submit: function(data) {
                this.refs.form.setFormPristine();
                var searchData;
                var orderStatus = this.state.userType === 1 ? this.state.statusList[this.state.active] : this.state.statusList[this.state.active + 1];
                if (data.orderNo.length) {
                    if (!data.orderNo.trim()) {
                        return;
                    }
                    searchData = { orderNo: data.orderNo.trim(), orderStatus: orderStatus };
                } else {
                    searchData = data;
                }
                searchData.startTime = this.refs.startTime.getValue();
                searchData.endTime = this.refs.endTime.getValue();
                this.setState({ searchData: searchData, current: 1 });
                this.search(searchData);
            },
            // 重置搜索
            resetForm: function() {
                this.refs.form.setFormPristine();
                this.refs.form.reset();

                this.refs.startTime.setValue(new Date().getBeforeDate(6)+' 00:00:00');
                this.refs.endTime.setValue(new Date().format("yyyy-MM-dd 23:59:59"));

                this.setState({ searchData: '', current: 1 });
                var orderStatus = this.state.userType === 1 ? this.state.statusList[this.state.active] : this.state.statusList[this.state.active + 1];
                this.search({ orderStatus: orderStatus, pageIndex: 1, pageSize: 10 ,startTime:new Date().getBeforeDate(6)+' 00:00:00',endTime:new Date().format("yyyy-MM-dd 23:59:59")});
            },
            // 翻页
            onPageChange: function(pageIndex, pageSize) {
                var orderStatus = this.state.userType === 1 ? this.state.statusList[this.state.active] : this.state.statusList[this.state.active + 1];
                var param = {
                    pageSize: pageSize,
                    pageIndex: pageIndex,
                    statusType: orderStatus,
                    orderNo: this.state.searchData ? this.state.searchData.orderNo : '',
                    startTime: this.state.searchData ? this.state.searchData.startTime : new Date().getBeforeDate(6)+' 00:00:00',
                    endTime: this.state.searchData ? this.state.searchData.endTime : new Date().format("yyyy-MM-dd 23:59:59")
                };
                this.setState({ pageSize: pageSize, current: pageIndex,selectItem:[],selectLength:0});
                this.search(param);
            },
            // 选中表格项目
            selectItemFn: function(item, e) {
                e.stopPropagation();
                var checked = e.target.checked;
                var selectItem = this.state.selectItem;
                var selectLength = this.state.selectLength;
                if (item === 'all') {
                    if (checked) {
                        selectItem = this.state.list.map(function(subject) {
                            return subject.orderNo;
                        });
                        selectLength = this.state.list.length;
                    } else {
                        selectItem = [];
                        selectLength = 0;
                    }
                } else {
                    if (checked) {
                        selectItem.push(item.orderNo);
                        selectLength += 1;
                    } else {
                        var index = selectItem.indexOf(item.orderNo);
                        selectItem.splice(index, 1);
                        selectLength -= 1;
                    }
                }
                this.setState({ selectItem: selectItem, selectLength: selectLength });
            },
            // 删除草稿订单
            deleteOrders: function() {
                var selectList = this.state.selectItem;
                var that = this;
                DialogComponent.init({
                    type: 'delete',
                    msg: '确定删除？',
                    success: function() {
                        order_manage_tradeService.deleteOrders(selectList, function(res) {
                            if (res.errorCode === 0) {
                                PromptComponent.init({
                                    type: 'success',
                                    msg: '操作成功'
                                }).show();
                                that.setState({ selectItem: [], selectLength: 0 });
                                that.search({ orderStatus: 'DRAFT', pageIndex: 1, pageSize: 10 });
                            } else {
                                PromptComponent.init({ type: 'warning', msg: res.msg }).show();
                            }
                        });
                    }
                }).show();
            },
            // 提交草稿订单
            submitOrders: function() {
                var selectList = this.state.selectItem;
                var that = this;
                DialogComponent.init({
                    type: 'confirm',
                    msg: '确定提交？',
                    success: function() {
                        order_manage_tradeService.submitOrders(selectList, function(res) {
                            if (res.errorCode === 0) {
                                PromptComponent.init({
                                    type: 'success',
                                    msg: '操作成功'
                                }).show();
                                that.setState({ selectItem: [], selectLength: 0 });
                                that.search({ orderStatus: 'DRAFT', pageIndex: 1, pageSize: 10 });
                            } else {
                                PromptComponent.init({ type: 'warning', msg: res.msg }).show();
                            }
                        });
                    }
                }).show();
            },
            // 确认订单
            confirmOrders: function() {
                var selectList = this.state.selectItem;
                var that = this;
                DialogComponent.init({
                    type: 'comfirm',
                    msg: '确定通过？',
                    success: function() {
                        order_manage_tradeService.confirmOrders(selectList, function(res) {
                            if (res.errorCode === 0) {
                                PromptComponent.init({
                                    type: 'success',
                                    msg: '操作成功'
                                }).show();
                                that.setState({ selectItem: [], selectLength: 0 });
                                that.search({ orderStatus: 'CONFIRMING', pageIndex: 1, pageSize: 10 });
                            } else {
                                PromptComponent.init({ type: 'warning', msg: res.msg }).show();
                            }
                        });
                    }
                }).show();
            },
            // 发货
            deliverOrders: function() {
                var selectList = this.state.selectItem;
                var that = this;
                DialogComponent.init({
                    type: 'comfirm',
                    msg: '确定发货？',
                    success: function() {
                        order_manage_tradeService.deliverOrders(selectList, function(res) {
                            if (res.errorCode === 0) {
                                PromptComponent.init({
                                    type: 'success',
                                    msg: '操作成功'
                                }).show();
                                that.setState({ selectItem: [], selectLength: 0 });
                                that.search({ orderStatus: 'DELIVERY', pageIndex: 1, pageSize: 10 });
                            } else {
                                PromptComponent.init({ type: 'warning', msg: res.msg }).show();
                            }
                        });
                    }
                }).show();
            },
            // 查询商品
            searchGoodsNo: function() {
                var that = this;
                selectFactory({
                    data: [],
                    id: 'goods',
                    isSearch: true,
                    closeLocalSearch: true,
                    defaultText:'',
                    pagination: true,
                    showTextField: 'name',
                    attrTextModel: function(name) {
                        that.refs.goodsId.setValue(name);
                    },
                    onSearchValueChange: function(attachEvent, data, currentPage) {
                        var param = {
                            q: data,
                            orderType: 'PURCHASE',
                            sellId: cookie.get('userId'),
                            purchaseId: that.state.sellId,
                            pageIndex: currentPage ? currentPage : 1,
                        };
                        order_manage_tradeService.searchGoodsNo(param, function(result) {
                            if (result.data.length) {
                                attachEvent.setData(result);
                                that.setState({ goodsInfo: result.data });
                            } else {
                                attachEvent.setData({ data: [] });
                                that.setState({ goodsInfo: [] });
                            }
                        });
                    }
                });
            },
            getPlat: function() {
                var that = this;
                order_manage_tradeService.getPlat(function(res) {
                    if (res.errorCode === 0) {
                        res.data.forEach(function(item) {
                            item.nameCode = item.name + '(' + item.code + ')';
                        });
                        res.data.unshift({nameCode: '全部', id: ''})
                        that.setState({ suppliers: res.data });
                        selectFactory({
                            data: res,
                            id: 'supplier',
                            defaultText: '',
                            showTextField: 'nameCode',
                            attrTextField: {
                                'data-id': 'id'
                            },
                            attrTextModel: function(name) {
                                that.refs.customerId.setValue(name);
                            },
                            attrTextId: function(id) {
                                that.setState({ sellId: id });
                            }
                        });
                    }
                });
            },
            // 贸易-客户-商品信息下拉列表
            getSuppliers: function() {
                var that = this;
                order_manage_tradeService.getPlat(function(res) {
                    if (res.errorCode === 0) {
                        //保存平台（供应商）数据
                        res.data.unshift({ name: '全部', id: '', code: '' });
                        that.setState({ suppliers: res.data });

                        var childEle = selectFactory({
                            data: {data: []},
                            id: 'goods',
                            isSearch: true,
                            closeLocalSearch: true,
                            pagination: true,
                            showTextField: 'name',
                            attrTextModel: function(name) {
                                that.refs.goodsId.setValue(name);
                            },
                            onSearchValueChange: function(attachEvent, data, currentPage) {
                                var param = { pageIndex: currentPage ? currentPage : 1 };
                                param.q = data;
                                if (cookie.get('userType') === '2' || cookie.get('userType') === '3') {
                                    param.orderType = 'SALE';
                                    param.sellId = that.state.sellId;
                                }
                                if (cookie.get('userType') === '256') {
                                    param.orderType = 'PURCHASE';
                                    param.purchaseId = that.state.sellId;
                                }
                                order_manage_tradeService.searchGoodsNo(param, function(res) {
                                    if (res.data.length) {
                                        attachEvent.setData(res);
                                        that.setState({ goodsInfo: res.data });
                                    } else {
                                        attachEvent.setData({ data: [] });
                                        that.setState({ goodsInfo: [] });
                                    }
                                });
                            }
                        });

                        var parentEle = selectFactory({
                            data: res,
                            id: 'supplier',
                            defaultText: '',
                            attrTextField: {
                                'data-id': 'id'
                            },
                            attrTextModel: function(name) {
                                that.refs.customerId.setValue(name);
                            },
                            attrTextId: function(id) {
                                that.setState({ sellId: id });
                                that.refs.goodsId.setValue('');
                                $('#goods').val('');
                                childEle.clearData();
                                var param = { q: '' };
                                if (cookie.get('userType') === '2' || cookie.get('userType') === '3') {
                                    param.orderType = 'SALE';
                                    param.sellId = id;
                                    param.purchaseId = cookie.get('userId');
                                }

                                if (cookie.get('userType') === '256') {
                                    param.orderType = 'PURCHASE';
                                    param.sellId = cookie.get('userId');
                                    param.purchaseId = id;
                                }
                                order_manage_tradeService.searchGoodsNo(param, function(res) {
                                    if (res.errorCode === 0 && res.data.length) {
                                        res.data.unshift({ name: '全部', id: '' });
                                        that.setState({ goodsInfo: res.data });
                                        childEle.setData(res);
                                    } else {
                                        // childEle.setData(res);
                                        // childEle.setData({data: []});
                                        childEle = null;
                                        that.setState({ goodsInfo: [] });
                                    }
                                });
                            }
                        });
                        parentEle.next = childEle;
                    }
                });
            },
            // 获取/查询子账号
            getSubAccount: function() {
                var that = this;
                order_manage_tradeService.getSubAccount('', function(res) {
                    if (!res.data) {
                        return;
                    }
                    res.data.forEach(function(item) {
                        item.nameCode = item.fullName + '(' + item.userName + ')';
                    });
                    res.data.unshift({ nameCode: '全部', id: '' });
                    that.setState({ userList: res.data });
                    selectFactory({
                        data: res,
                        id: 'username',
                        isSearch: true,
                        pagination: true,
                        defaultText: '',
                        searchPlaceHoder: '请输入姓名或用户名',
                        showTextField: 'nameCode',
                        closeLocalSearch: true,
                        attrTextModel: function(nameCode) {
                            that.refs.cusUserId.setValue(nameCode);
                        },
                        onSearchValueChange: function(attachEvent, data, currentPage) {
                            order_manage_tradeService.getSubAccount({ q: data, pageIndex: currentPage ? currentPage : 1 }, function(result) {
                                if (!result.data.length) {
                                    return;
                                }
                                result.data.forEach(function(item) {
                                    item.nameCode = item.fullName + '(' + item.userName + ')';
                                });
                                result.data.unshift({ nameCode: '全部', id: '' });
                                attachEvent.setData(result);
                                that.setState({ userList: result.data });
                            });
                        }
                    });
                });
            },

            /* getorderStatus: function () {
            var that = this;
            order_manage_tradeService.getOrderStatus('', function (res) {
                if (res.errorCode === 0) {
                    that.setState({ statusList: res.data });
                     selectFactory({
                        data: res,
                        id: 'statusList',
                        offset: -300,
                        isSearch: true,
                        defaultText: '',
                        showTextField: 'name',
                        attrTextModel: function (code) {
                            that.refs.orderStatus.setValue(code);
                        }
                    });
                }
            });
        }, */

            render: function() {
                var Browser = typeof window != 'undefined';
                var component = this;
                return ~init;
            }
        });
        if (typeof Object.assign != 'function') {
            Object.assign = function(target, varArgs) {
                'use strict';
                if (target == null) {
                    // TypeError if undefined or null
                    throw new TypeError('Cannot convert undefined or null to object');
                }
                var to = Object(target);
                for (var index = 1; index < arguments.length; index++) {
                    var nextSource = arguments[index];
                    if (nextSource != null) {
                        // Skip over if undefined or null
                        for (var nextKey in nextSource) {
                            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                                to[nextKey] = nextSource[nextKey];
                            }
                        }
                    }
                }
                return to;
            };
        }
        if (typeof ReactDOM != 'undefined') {
            ReactDOM.render(<PageComponent data={storage} />, document.getElementById('container'));
        }
        module.exports = PageComponent;
    }
);
